import React, { Component } from 'react';
import { Table, Space, Button, Form, Input, Modal, Breadcrumb, DatePicker, Pagination, Divider, message, Popconfirm } from 'antd';
import { FormOutlined, DeleteOutlined, PlusOutlined, AppstoreTwoTone } from '@ant-design/icons';
import { connect } from 'dva'
import styles from "./index.less"
import 'braft-editor/dist/index.css';
import BraftEditor from 'braft-editor';
import CreateForm from './create'
const { RangePicker } = DatePicker
@connect(() => ({}))
class ArticleListForm extends Component {
  constructor(props) {
    super(props)
    this.state = {
      total: 0,
      currentPage: 0,
      pageSize: 5,
      modalTitle: "科研软件新增",
      editorState: BraftEditor.createEditorState(null),
      isModalVisible: false,
      loading: false,
      form: {
        author: "",
        startTime: "",
        endTime: "",
      },
      rangeTimeValue: "",
      data: [],//表数据
      softwareDetail: [],//编辑数据
      typeTreeData: []
    }
  }
  componentDidMount() {
    this.getSoftWareList()
  }
  getTypeTree = () => {
    this.props.dispatch({
      type: "global/getDirs",
      payload: {

      }
    }).then(res => {
      console.log(res)
      this.setState({
        typeTreeData: res.data
      })
    })
  }
  searchSoftWareList=()=>{
    this.setState({
      currentPage:1
    },()=>{
      this.getSoftWareList()
    })
  }
  //获取列表
  getSoftWareList = () => {
    console.log(this.state.form)
    const { form, currentPage, pageSize } = this.state
    this.props.dispatch({
      type: "global/getKnowledgeByPage",
      payload: {
        pageSize: pageSize,
        currentPage: currentPage === 0 ? 1 : currentPage,
        author: form.author,
        startTime: form.startTime,
        endTime: form.endTime,
        type: ""
      }
    }).then(res => {
      console.log(res)
      if (res) {
        this.getTypeTree()
        res.data.rows.map((item, index) => {
          item.key = item.id
          this.state.typeTreeData && this.state.typeTreeData.map(item2 => {
            if (item.type === item2.code) {
              item.mytype = item2.name
            } else {
              item2.children.map(item3 => {
                if (item.type === item3.code) {
                  item.mytype = item3.name
                }
              })
            }
          })
        })
        console.log(res.data.rows)
        this.setState({
          data: res.data.rows,
          total: res.data.total
        })
      }
    })
  }
  //清空
  clearEvent = () => {
    this.setState({
      form: {
        author: "",
        startTime: "",
        endTime: "",
      },
      rangeTimeValue: new Date()//清空
    }, () => this.getSoftWareList())

  }
  //发布时间选择
  releaseTimeChange = (_, dateStrings) => {
    this.setState({
      form: {
        ...this.state.form,
        startTime: dateStrings[0],
        endTime: dateStrings[1],
        currentPage: 0
      },
    })
  }
  //新增
  createEvent = () => {
    this.setState({
      isModalVisible: true,
      editorState: BraftEditor.createEditorState(null),
      softwareDetail: {}
    })
  }

  //编辑按钮
  editorEvent = (record) => {
    this.props.dispatch({
      type: "global/getKnowledgeInfo",
      payload: {
        id: record.id
      }
    }).then(res => {
      if (res) {
        // const htmlstring = `<p>${record.heading}</p>`
        this.setState({
          // editorState: BraftEditor.createEditorState(htmlstring),
          softwareDetail: { ...res.data, id: record.id },
          isModalVisible: true,
          modalTitle: "科研软件编辑"
        })
      }
    })
  }
  //删除
  deleteEvent = (record) => {
    this.props.dispatch({
      type: "global/deleteKnowledge",
      payload: {
        id: record.id
      }
    }).then(res => {
      if (res) {
        this.getSoftWareList()
        message.success("删除成功！")
      }
    })
  }

  //弹框确定按钮
  handleOk = () => {
    this.setState({
      isModalVisible: false
    })
  }
  //弹框取消按钮
  handleCancel = () => {
    this.setState({
      isModalVisible: false
    })
  }
  handleAuthorChange = (e) => {
    this.setState({
      form: {
        ...this.state.form,
        author: e.target.value
      },
      currentPage: 0
    })
  }
  //分页
  pageChange = (page, pageSize) => {
    console.log(page, pageSize)
    this.setState({ pageSize: pageSize, currentPage: page }, () => { this.getSoftWareList() })
  }
  //
  pageSizeChange = (current, size) => {
    // console.log(size)
    this.setState({ pageSize: size, currentPage: 1 }, () => { this.getSoftWareList() })
  }

  render() {
    let { data, isModalVisible, form, rangeTimeValue, modalTitle, softwareDetail, total,currentPage } = this.state;

    const routes = [{ path: '', breadcrumbName: '科研软件管理', }, { path: '', breadcrumbName: '科研软件列表', }]
    //表头数据  key唯一
    const columns = [
      {
        title: '编号',
        dataIndex: 'num',
        key: 'num',
        align: "center",
        render: (text, record, index) => `${index + 1}`,
        width: 100
      },
      {
        title: '标题',
        dataIndex: 'title',
        align: "center",
        key: 'title',
      },
      {
        title: '浏览量',
        dataIndex: 'visitNum',
        align: "center",
        key: 'visitNum',
        width: 200
      },
      {
        title: '发布人',
        dataIndex: 'author',
        align: "center",
        key: 'author',
        width: 200
      },
      {
        title: '软件类别',
        dataIndex: 'name',
        align: "center",
        key: 'name',
        width: 200
      },
      {
        title: '发布时间',
        key: 'releaseTime',
        align: "center",
        dataIndex: 'releaseTime',
        width: 200
      },
      {
        title: '操作',
        key: 'action',
        align: "center",
        width: 400,
        render: (text, record) => (
          <Space size="middle">
            <Button type="primary"
              icon={<FormOutlined />}
              size="small" shape="round"
              style={{ background: "#11bf94" }}
              onClick={() => this.editorEvent(record)}>编辑</Button>
            {/* <Button type="primary" size="small" shape="round">编辑</Button> */}
            <Popconfirm title="是否确实删除?" onConfirm={() => this.handleDelete(record)}>
            <Button type="primary"
              icon={<DeleteOutlined />}
              danger
              size="small"
              shape="round"
              // onClick={() => this.deleteEvent(record)}
              >删除</Button>
            </Popconfirm>
          </Space>
        ),
      },
    ];

    return (
      <div>
        <div className={styles.pagetop}>
          <span className={styles.pageheader}>
            <Breadcrumb>
              <Breadcrumb.Item><AppstoreTwoTone />科研软件管理</Breadcrumb.Item>
              <Breadcrumb.Item>
                <a href="/article/index">科研软件列表</a>
              </Breadcrumb.Item>
            </Breadcrumb>
          </span>
        </div>
        <div style={{ background: "white" }}>
          <div className={styles.form}>
            <Form
              layout="inline"
            >
              <Form.Item
                label="发布人"
              // name="username"
              // rules={[{ required: true, message: 'Please input your username!' }]}
              >
                <Input
                  placeholder="请输入发布人"
                  value={form.author}
                  onChange={this.handleAuthorChange}
                />
              </Form.Item>
              <Form.Item
                label="发布时间"
              >
                <RangePicker
                  key={rangeTimeValue}
                  showTime
                  format="YYYY/MM/DD HH:mm:ss"
                  onChange={this.releaseTimeChange}
                />
              </Form.Item>
              <Form.Item>
                <Button type="primary" onClick={this.searchSoftWareList}>查询</Button>
                <Button type="default" style={{ marginLeft: "10px" }} onClick={this.clearEvent}>清空</Button>
              </Form.Item>
            </Form>
          </div>
          <Divider />
          <Button type="primary" icon={<PlusOutlined />} style={{ marginLeft: "20px" }} onClick={this.createEvent}>新增</Button>
          <Table
            columns={columns}
            dataSource={data}
            pagination={false}
          />
        </div>
        <div className={styles.pagination}>
          <Pagination
            total={total}
            showSizeChanger
            showQuickJumper
            current={currentPage===0?1:currentPage}
            defaultCurrent={1}
            defaultPageSize={5}
            pageSizeOptions={[5, 10, 20, 50]}
            showTotal={total => `共 ${total} 条`}
            onChange={this.pageChange}
            onShowSizeChange={this.pageSizeChange}
          />
        </div>
        {/* 科研编辑弹框 */}
        <Modal
          title={modalTitle}
          visible={isModalVisible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width={1000}
          footer={false}>
          <CreateForm
            key={new Date()}
            handleCancel={this.handleCancel}
            handleOk={this.handleOk}
            getSoftWareList={this.getSoftWareList}
            softwareDetail={softwareDetail}
          />
        </Modal>
      </div>
    );
  }
}

export default ArticleListForm;